"use client"

import { Button } from "@/components/ui/button"
import { useState, useEffect } from "react"
import { Checkbox } from "@/components/ui/checkbox"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, Plus, ChevronLeft, ChevronRight, Beaker, AlertCircle, User } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { format } from "date-fns"
import { apiClient } from "@/lib/api"
import { transformToGroupedData } from "@/lib/data-utils"
import type { Sample, SampleFilters, SampleGroup, BackendPaginatedResponse, ApiResponse } from "@/types"

export default function SampleMixingPage() {
  const [groups, setGroups] = useState<SampleGroup[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedSamples, setSelectedSamples] = useState<string[]>([])
  const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null)
  const [isShiftPressed, setIsShiftPressed] = useState(false)

  // 筛选和分页状态
  const [searchTerm, setSearchTerm] = useState("")
  const [startDate, setStartDate] = useState<Date | undefined>(undefined)
  const [endDate, setEndDate] = useState<Date | undefined>(undefined)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [totalGroups, setTotalGroups] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [totalSamples, setTotalSamples] = useState(0)

  // 对话框状态
  const [mixedGroupSize, setMixedGroupSize] = useState(3)
  const [showMixedDialog, setShowMixedDialog] = useState(false)

  // 统计数据
  const [stats, setStats] = useState({
    unassigned: 0,
    total: 0,
  })

  // 监听Shift键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(true)
    }
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(false)
    }

    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)
    return () => {
      window.removeEventListener("keydown", handleKeyDown)
      window.removeEventListener("keyup", handleKeyUp)
    }
  }, [])

  // 获取未分配样品数据
  const fetchSamples = async () => {
    setLoading(true)
    try {
      const filters: SampleFilters = {
        search: searchTerm,
        status: "unassigned",
        startDate: startDate?.toISOString(),
        endDate: endDate?.toISOString(),
        page: currentPage,
        pageSize: pageSize,
      }

      const queryParams = new URLSearchParams()
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
          queryParams.append(key, value.toString())
        }
      })

      const result: ApiResponse<BackendPaginatedResponse<Sample>> = await apiClient.get(`/samples?${queryParams}`)

      if (result.success && result.data) {
        const backendData = result.data

        // 转换为前端分组格式
        const transformedData = transformToGroupedData(backendData, "unassigned")

        setGroups(transformedData.groups)
        setTotalGroups(transformedData.total)
        setTotalPages(transformedData.totalPages)
        setTotalSamples(transformedData.totalSamples)
      }
    } catch (error) {
      console.error("获取样品数据失败:", error)
    } finally {
      setLoading(false)
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      // 注意：这里应该定义具体的StatsResponse类型，暂时使用any
      const result: ApiResponse<any> = await apiClient.get("/samples/stats")
      if (result.success && result.data) {
        setStats({
          unassigned: result.data.unassigned,
          total: result.data.total,
        })
      }
    } catch (error) {
      console.error("获取统计数据失败:", error)
    }
  }

  useEffect(() => {
    fetchSamples()
  }, [currentPage, pageSize, searchTerm, startDate, endDate])

  useEffect(() => {
    fetchStats()
  }, [])

  // 获取所有样品（用于选择操作）
  const getAllSamples = (): Sample[] => {
    return groups.flatMap((group) => group.samples)
  }

  // 处理单个样品选择
  const handleSelectSample = (sampleId: string, checked: boolean, index: number) => {
    const allSamples = getAllSamples()

    if (isShiftPressed && lastSelectedIndex !== null) {
      const currentSampleIndex = allSamples.findIndex((s) => s.id === sampleId)
      const lastSampleIndex = lastSelectedIndex

      if (currentSampleIndex !== -1 && lastSampleIndex !== -1) {
        const start = Math.min(lastSampleIndex, currentSampleIndex)
        const end = Math.max(lastSampleIndex, currentSampleIndex)
        const rangeIds = allSamples.slice(start, end + 1).map((s) => s.id)
        const newSelected = [...new Set([...selectedSamples, ...rangeIds])]
        setSelectedSamples(newSelected)
      }
    } else {
      if (checked) {
        setSelectedSamples([...selectedSamples, sampleId])
      } else {
        setSelectedSamples(selectedSamples.filter((id) => id !== sampleId))
      }
      const currentIndex = allSamples.findIndex((s) => s.id === sampleId)
      setLastSelectedIndex(currentIndex)
    }
  }

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const allSampleIds = getAllSamples().map((s) => s.id)
      setSelectedSamples(allSampleIds)
    } else {
      setSelectedSamples([])
    }
  }

  // 生成混合编号
  const generateMixedNumbers = async () => {
    if (selectedSamples.length === 0) {
      alert("请先选择要进行混样处理的样品")
      return
    }

    try {
      const result: ApiResponse<void> = await apiClient.post("/samples/generate-mixed", {
        sampleIds: selectedSamples,
        groupSize: mixedGroupSize,
      })

      if (result.success) {
        alert(result.message)
        setSelectedSamples([])
        setShowMixedDialog(false)
        fetchSamples()
        fetchStats()
      } else {
        alert(result.message || "混样处理失败")
      }
    } catch (error) {
      alert("网络错误，请稍后重试")
    }
  }

  const allSamples = getAllSamples()
  const isAllSelected = allSamples.length > 0 && selectedSamples.length === allSamples.length
  const isPartialSelected = selectedSamples.length > 0 && selectedSamples.length < allSamples.length

  return (
      <div className="p-6 space-y-6">
        {/* 页面标题 */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <Beaker className="h-7 w-7 text-blue-600" />
              样品混样处理
            </h1>
            <p className="text-muted-foreground">对未分配的样品进行混样编号分配和批次管理</p>
          </div>
          <Dialog open={showMixedDialog} onOpenChange={setShowMixedDialog}>
            <DialogTrigger asChild>
              <Button disabled={selectedSamples.length === 0} className="bg-blue-600 hover:bg-blue-700">
                <Plus className="w-4 h-4 mr-2" />
                分配混样编号 ({selectedSamples.length})
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>样品混样编号分配</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="groupSize">混样组合数量</Label>
                  <Select value={mixedGroupSize.toString()} onValueChange={(value) => setMixedGroupSize(Number(value))}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="2">2个样品混合一组</SelectItem>
                      <SelectItem value="3">3个样品混合一组</SelectItem>
                      <SelectItem value="4">4个样品混合一组</SelectItem>
                      <SelectItem value="5">5个样品混合一组</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    已选择 {selectedSamples.length} 个待混样样品，将生成{" "}
                    {Math.ceil(selectedSamples.length / mixedGroupSize)} 个混样编号组
                  </AlertDescription>
                </Alert>
                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={() => setShowMixedDialog(false)}>
                    取消
                  </Button>
                  <Button onClick={generateMixedNumbers} className="bg-blue-600 hover:bg-blue-700">
                    确认分配
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {/* 统计信息 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="border-l-4 border-gray-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">待混样样品总数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-gray-600">{stats.unassigned}</div>
              <div className="text-xs text-muted-foreground mt-1">等待混样编号分配</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-blue-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">当前页样品数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-blue-600">{totalSamples}</div>
              <div className="text-xs text-muted-foreground mt-1">本页显示的样品数量</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-green-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">已选择样品</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{selectedSamples.length}</div>
              <div className="text-xs text-muted-foreground mt-1">
                {selectedSamples.length > 0 && `可生成 ${Math.ceil(selectedSamples.length / mixedGroupSize)} 个混样组`}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 搜索和筛选条件 */}
        <div className="flex gap-4 items-center flex-wrap">
          <Input
              placeholder="搜索样品编号、名称、录入人..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-64"
          />

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" size="icon">
                <Calendar className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <div className="p-3 border-b">
                <div className="text-sm font-medium">样品录入时间范围</div>
              </div>
              <div className="p-3 flex flex-col gap-2">
                <div>
                  <div className="text-xs mb-1">开始日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={startDate}
                      onSelect={setStartDate}
                      className="border rounded-md"
                  />
                </div>
                <div>
                  <div className="text-xs mb-1">结束日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={endDate}
                      onSelect={setEndDate}
                      className="border rounded-md"
                  />
                </div>
                <div className="flex justify-end">
                  <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setStartDate(undefined)
                        setEndDate(undefined)
                      }}
                  >
                    重置
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>

          <Select value={pageSize.toString()} onValueChange={(value) => setPageSize(Number(value))}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="10">10条/页</SelectItem>
              <SelectItem value="20">20条/页</SelectItem>
              <SelectItem value="50">50条/页</SelectItem>
              <SelectItem value="100">100条/页</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* 样品表格 */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
                <div className="flex items-center justify-center h-64">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                </div>
            ) : totalSamples === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                  <Beaker className="h-12 w-12 mb-4" />
                  <p className="text-lg font-medium">暂无待混样样品</p>
                  <p className="text-sm">所有样品都已完成混样编号分配</p>
                </div>
            ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-gray-100">
                        <TableHead className="w-12">
                          <Checkbox
                              checked={isAllSelected}
                              {...(isPartialSelected ? { indeterminate: true } : {})}
                              onCheckedChange={handleSelectAll}
                          />
                        </TableHead>
                        <TableHead>样品编号</TableHead>
                        <TableHead>样品名称</TableHead>
                        <TableHead>样品类型</TableHead>
                        <TableHead>送检单位</TableHead>
                        <TableHead>录入人</TableHead>
                        <TableHead>录入时间</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {groups.flatMap((group) =>
                          group.samples.map((sample, index) => {
                            const isSelected = selectedSamples.includes(sample.id)
                            return (
                                <TableRow
                                    key={sample.id}
                                    className={isSelected ? "bg-blue-50" : "bg-gray-50 hover:bg-gray-100"}
                                >
                                  <TableCell>
                                    <Checkbox
                                        checked={isSelected}
                                        onCheckedChange={(checked) => handleSelectSample(sample.id, checked as boolean, index)}
                                    />
                                  </TableCell>
                                  <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                                  <TableCell>{sample.sampleName}</TableCell>
                                  <TableCell>{sample.sampleType}</TableCell>
                                  <TableCell>{sample.testingUnit}</TableCell>
                                  <TableCell>
                                    <div className="flex items-center gap-2">
                                      <User className="h-4 w-4 text-muted-foreground" />
                                      {sample.inputOperator || "系统录入"}
                                    </div>
                                  </TableCell>
                                  <TableCell>
                                    {sample.inputTime ? format(new Date(sample.inputTime), "yyyy-MM-dd HH:mm") : "-"}
                                  </TableCell>
                                </TableRow>
                            )
                          }),
                      )}
                    </TableBody>
                  </Table>

                  {/* 分页控件 */}
                  <div className="flex items-center justify-between px-6 py-4 border-t">
                    <div className="text-sm text-muted-foreground">
                      显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalGroups)} 条，共{" "}
                      {totalSamples} 个待混样样品
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                          disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                        上一页
                      </Button>
                      <div className="flex items-center gap-1">
                        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                          let pageNum
                          if (totalPages <= 5) {
                            pageNum = i + 1
                          } else if (currentPage <= 3) {
                            pageNum = i + 1
                          } else if (currentPage >= totalPages - 2) {
                            pageNum = totalPages - 4 + i
                          } else {
                            pageNum = currentPage - 2 + i
                          }

                          return (
                              <Button
                                  key={pageNum}
                                  variant={currentPage === pageNum ? "default" : "outline"}
                                  size="sm"
                                  onClick={() => setCurrentPage(pageNum)}
                                  className="w-8 h-8 p-0"
                              >
                                {pageNum}
                              </Button>
                          )
                        })}
                      </div>
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                          disabled={currentPage === totalPages}
                      >
                        下一页
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </>
            )}
          </CardContent>
        </Card>

        {/* 操作说明 */}
        <Card>
          <CardContent className="p-4">
            <div className="text-sm space-y-2">
              <div>
                <strong>混样处理说明：</strong>
              </div>
              <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                <li>选择需要进行混样处理的样品，可以使用Shift键进行范围选择</li>
                <li>点击"分配混样编号"按钮，设置每组混样的样品数量</li>
                <li>系统将按照设置的数量自动分组并生成混样编号（MX001、MX002...）</li>
                <li>混样完成后的样品将进入"质控抽检处理"流程</li>
                <li>混样编号用于标识同一批次处理的样品组合</li>
              </ul>
            </div>
          </CardContent>
        </Card>
      </div>
  )
}
